Page({
  data:{
    appId:'',
    appName:'',
    records:[],
    allRecords:[],
    statusFilter:'all',
    searchKeyword:'',
    loading:true,
    loadmoreShow:false,
    loadmoreType:'loading',
    hasMore:true
  },
  onLoad(options){
    const appId=options.appId||options.app_id||''
    const appName=decodeURIComponent(options.appName||options.app_name||'')
    this.setData({appId,appName})
    this.loadRecords()
  },
  loadRecords(){
    const list=this.getMockRecordsByAppId(this.data.appId)
    this.setData({allRecords:list,loading:false})
    this.applyFilters()
  },
  getMockRecordsByAppId(appId){
    const id=String(appId)
    const base=(t)=>[
      {id:'1',title:`${t}申请单-001`,status:'pending',statusText:'待处理',applicant:'庄嘉豪',date:'2025-11-27'},
      {id:'2',title:`${t}申请单-002`,status:'approved',statusText:'已通过',applicant:'李四',date:'2025-11-20'},
      {id:'3',title:`${t}申请单-003`,status:'rejected',statusText:'已驳回',applicant:'王五',date:'2025-11-18'}
    ]
    const map={
      '27':base('车辆设备'),
      '28':base('会议申请'),
      '29':base('支出预算'),
      '30':base('人员需求'),
      '31':base('员工假期'),
      '32':base('员工辞职'),
      '33':base('合同申请'),
      '34':base('印章借用'),
      '36':base('物资采购'),
      '37':base('物资领用'),
      '38':base('差旅费报销'),
      '39':base('费用报销'),
      '40':base('请款申请'),
      '41':base('借款申请'),
      '42':base('经代缴款')
    }
    return map[id]||base('通用申请')
  },
  applyFilters(){
    const kw=this.data.searchKeyword.trim().toLowerCase()
    const status=this.data.statusFilter
    let list=[...this.data.allRecords]
    if(status!=='all') list=list.filter(r=>r.status===status)
    if(kw) list=list.filter(r=>`${r.title}${r.applicant}${r.statusText}`.toLowerCase().includes(kw))
    this.setData({records:list})
  },
  onSearchChange(e){
    this.setData({searchKeyword:e.detail.value||''})
    this.applyFilters()
  },
  onSearch(e){
    this.setData({searchKeyword:e.detail.value||''})
    this.applyFilters()
  },
  onFilterChange(e){
    this.setData({statusFilter:e.detail.activeKey||'all'})
    this.applyFilters()
  },
  onRecordTap(e){
    const record=e.currentTarget.dataset.record
    wx.navigateTo({
      url:`/pages/main/common-record-detail/common-record-detail?appId=${this.data.appId}&appName=${encodeURIComponent(this.data.appName)}&recordId=${record.id}`
    })
  },
  onReachBottom(){
    if(this.data.hasMore){
      this.setData({loadmoreShow:true,loadmoreType:'loading'})
      setTimeout(()=>{
        this.setData({hasMore:false,loadmoreType:'end'})
      },800)
    }else{
      this.setData({loadmoreShow:true,loadmoreType:'end'})
    }
  }
})
